package fr.web325.servlet.client.login;

import fr.web325.bean.User;
import fr.web325.dao.UserDao;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/shop/client/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = null;
        List cart = null;
        try {
            user = new UserDao().Login(req.getParameter("username"), req.getParameter("password"));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (user == null) {
            // 登陆失败
            req.setAttribute("msg","请检查账户或密码后重试!<a href=\""+req.getContextPath()+"/shop/client/login.jsp\">点击返回继续登录</a>");
            req.getRequestDispatcher("/shop/client/tips.jsp").forward(req,resp);
            return;
        }
        // 未激活,提示到邮箱中激活
        if(user.getState() == 0){
            req.setAttribute("msg","<h4>请到注册的邮箱进行激活后在登录,邮箱号"+user.getEmail()+"</h4>");
            req.getRequestDispatcher("/shop/client/tips.jsp").forward(req,resp);
            return;
        }
        // 是否记住密码
        if(req.getParameter("remember")!=null && req.getParameter("remember").equals("on")){
            resp.addCookie(new Cookie("username", user.getUsername()));
            resp.addCookie(new Cookie("password", user.getPASSWORD()));
        }else{
            resp.addCookie(new Cookie("username", ""));
            resp.addCookie(new Cookie("password", ""));
        }

        //将数据存储到session中
        HttpSession session = req.getSession();
        session.setAttribute("user", user);
        session.setAttribute("cart", null);
        session.setMaxInactiveInterval(60*60*24);
        if (user.getRole().equals("超级用户")) {
            // 是超级用户则跳转后台
            resp.sendRedirect(req.getContextPath()+"/shop/admin/goods");
        } else {
            // 跳回首页
            req.getRequestDispatcher("/shop").forward(req, resp);
        }
    }
}
